<template>
  <ych-modal
    :fullscreen="false"
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item :label="$t('m.eform.apptable.entity.objName')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'objName', validatorRules.objName]" :placeholder="$t('m.eform.formDesign.label.qing-shu-ru-er-mo-xing-ming-cheng')"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('m.eform.apptable.entity.objCode')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'objCode', validatorRules.objCode]" :placeholder="$t('m.eform.formDesign.label.qing-shu-ru-er-mo-xing-biao-shi')"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]" style="width: 100%;"></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-show="false">
            <a-form-item :label="$t('m.eform.apptable.entity.persistenceType')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="['persistenceType', validatorRules.persistenceType]" :placeholder="$t('m.eform.formDesign.label.qing-xuan-ze-chi-jiu-hua-fang-shi')">
                <a-select-option v-for="item in persistenceType" :key="item.value" :value="item.value">
                  {{item.text}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <obj-relation-table ref="objRelationTable"
                          :obj-relation="model.objRelation"
                          @change="setObjRelation"
                          :groupId="groupId"/>
    </a-spin>
  </ych-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ObjRelationTable from './actAppObject/ObjRelationTable'
  import { EFormConstant } from '../EFormConstant'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'ActAppObjectModal',
    components: {
      ObjRelationTable,
    },
    props: {
      groupId: {
        type: String,
        required: true
      },
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: this.$t('m.common.label.operate'),
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          objName: { rules: [{ required: true, message: this.$t('m.eform.formDesign.label.qing-shu-ru-er-mo-xing-ming-cheng') }] },
          objCode: { rules: [{ required: true, message: this.$t('m.eform.formDesign.label.qing-shu-ru-er-mo-xing-biao-shi') }, { validator: this.checkCode }] },
          persistenceType: {
            initialValue: 'db'
          },
          orderNum: {
            initialValue: 1 // TODO 默认值取数据库最大值+10
          },
        },
        persistenceType: EFormConstant.persistenceType,
        url: {
          add: YchConstant.PREFIX_EFORM + '/manage/actAppObject/add',
          edit: YchConstant.PREFIX_EFORM + '/manage/actAppObject/edit',
          checkCode: YchConstant.PREFIX_EFORM + '/manage/actAppObject/checkCode',
        }
      }
    },
    methods: {
      add () {
        this.edit({})
      },
      edit (record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'objName', 'objCode', 'persistenceType', 'orderNum'))
          this.$refs.objRelationTable.init(this.model.objRelation)
        })
      },
      close () {
        this.$emit('close')
        this.visible = false
        this.$refs.objRelationTable.visible = false
      },
      validObjRelation(data) {
        if (!data || data.length === 0) {
          return true;
        }
        for (let i = 0; i < data.length; i++) {
          if (!data[i].tableKey || !data[i].type) {
            return false;
          }
          if (data[i].type !== "main") {
            if (!data[i].fks || data[i].fks.length === 0) {
              return false
            }
            const validFks = this.validFks(data[i].fks)
            if (!validFks) {
              return false
            }
          }
          const validFlg = this.validObjRelation(data[i].children)
          if (!validFlg) {
            return false
          }
        }
        return true;
      },
      validFks(fks) {
        for (let i = 0; i < fks.length; i++) {
          if (!fks[i].from || !fks[i].type || !fks[i].value) {
            return false
          }
        }
        return true
      },
      handleOk () {
        const that = this

        // 校验ER模型对象
        if(!this.model.objRelation){
          this.messageUtil.warning(this.$t('m.eform.formDesign.label.er-mo-xing-wei-she-zhi'))
          return;
        }
        const objRelationJson = JSON.parse(this.model.objRelation)
        const objRelationData = [objRelationJson]
        let flg = this.validObjRelation(objRelationData)
        if(!flg){
          this.messageUtil.warning(this.$t('m.eform.formDesign.label.er-mo-xing-she-zhi-bu-he-fa'))
          return
        }

        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            formData.groupId = this.groupId
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message)
                that.$emit('ok')
              } else {
                that.messageUtil.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      setObjRelation (objRelation) {
        this.model.objRelation = objRelation
        if (objRelation.indexOf(EFormConstant.objStructure_oneToMany) != -1) {
          this.model.objStructure = EFormConstant.objStructure_oneToMany
        } else if (objRelation.indexOf(EFormConstant.objStructure_oneToOne) != -1) {
          this.model.objStructure = EFormConstant.objStructure_oneToOne
        } else {
          this.model.objStructure = EFormConstant.objStructure_main
        }
      },
      checkCode (rule, value, callback) {
        if (!value) {
          callback()
          return
        }
        let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if(reg.test(value)){
          callback(this.$t('m.eform.formDesign.label.er-mo-xing-biao-shi-bu-neng-bao-han-han-zi'))
          return
        }
        getAction(this.url.checkCode, {
          value: value,
          id: this.model.id
        }).then((res) => {
          res.success ? callback() : callback(res.message)
        })
      }
    }
  }
</script>
